<!-- 房屋管理 -->
<template>
  <div>
    <div class="header">
      <div class="title" style="height: 65px">
        <div style="margin-bottom: 5px; margin-top: 5px">
          <a-space style="margin-left: 10px">
            <span>开始时间：</span>
            <a-date-picker v-model:value="startDate" :format="dateFormat" />
          </a-space>
          <a-space style="margin-left: 10px">
            <span>结束时间：</span>
            <a-date-picker v-model:value="endDate" :format="dateFormat" />
          </a-space>
          <a-space style="margin-top: 15px; margin-left: 25px">
            <span>核验来源：</span>
            <a-select ref="select" v-model:value="role_type" style="width: 120px">
              <a-select-option value="6">自查</a-select-option>
              <a-select-option value="5">村级</a-select-option>
              <a-select-option value="4">乡镇</a-select-option>
              <a-select-option value="3">区级</a-select-option>
              <a-select-option value="2">市级</a-select-option>
            </a-select>
          </a-space>
          <a-space style="margin-top: 15px; margin-left: 15px">
            <span>核验人员姓名：</span>
            <a-input
              v-model:value="nickname"
              placeholder="请输入核查人员姓名进行查询"
              style="width: 256px; margin-top: -10px"
            />
          </a-space>
          <a-space style="margin-left: 10px; margin-top: 15px">
            <span>关键字：</span>
            <a-input
              v-model:value="txtKeyWord"
              placeholder="请输入姓名、地址或房屋编号进行查询"
              style="width: 300px; margin-top: -10px"
            />
          </a-space>
          <a-space class="search-btn" style="margin-left: 10px">
            <a-checkbox v-model:checked="checked">重点村</a-checkbox>
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <a-space class="search-btn">
            <a-button type="primary" @click="searchBtn">查询</a-button>
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <space style="float: right; margin-right: 10px; margin-top: 15px">
            <a-button type="primary" @click="handleExport"> 导出统计表</a-button>
          </space>
        </div>
      </div>
      <div style="width: 100%; background: #fff; height: 40px">
        <div style="width: 30%; float: left; font-size: 16px; padding-left: 20px; line-height: 37px"
          ><home-outlined two-tone-color="#eb2f96" /><span style="padding: 0px 10px">
            {{ title }}</span
          ></div
        >
        <div
          style="
            width: 30%;
            float: right;
            font-size: 16px;
            padding-left: 20px;
            line-height: 37px;
            text-align: right;
            padding-right: 20px;
          "
          ><a style="color: blue" @click="getBack"
            ><arrow-left-outlined two-tone-color="#eb2f96" style="padding: 0px 10px" />返回上一页</a
          ></div
        >
      </div>
      <a-table
        :dataSource="tableData"
        :columns="displayColumns"
        :pagination="false"
        :scroll="{ x: 1500, y: detailTableHeight }"
        bordered
        :loading="loading"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import moment from 'moment';
  import dayjs from 'dayjs';
  import { ref, reactive, toRefs, onMounted, onBeforeMount, computed } from 'vue';
  import { createFromIconfontCN } from '@ant-design/icons-vue';
  import { HousetownStdList, getRegion } from '/@/api/demo/api'; //统计工作进展
  import { useUserStore } from '/@/store/modules/user';
  import { useRouter } from 'vue-router';
  import { iTableData, iTableColumns } from './types/table';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useCheckStore } from '/@/store/modules/checkStore';
  let userInfo = ref<any>(null);
  const router = useRouter();
  const nickname = ref<string>(''); //核验人员姓名
  const txtKeyWord = ref<string>(''); //关键字
  const role_type = ref<string>('3'); //关键字
  const title = ref<string>(''); //关键字
  let detailTableHeight = ref<number>(800); // 表格高度
  let tableHeight = ref<number>(0); // 表格高度
  const dateFormat = 'YYYY-MM-DD';
  const startDate = ref<any>(null); // 开始时间
  const endDate = ref<any>(null); // 结束时间
  const checked = ref(false);
  let pageIndex = ref(1);
  let pageSize = ref(100);
  const userStore = useUserStore();
  const globSetting = useGlobSetting();
  const store = useCheckStore();
  const IconFont = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js',
  });
  const { startTime, endTime, currentTitle, xzqdm,cked } = store.formData || {};
  let data = reactive<{
    tableData: iTableData[];
    tableColumns: iTableColumns[];
    wscolsList: { wch: number }[];
    id: number | any;
    loading: Boolean;
    keyWorld: String;
    currentqx: string; // 当前行政区名称

    cityToken: string | any;
    startTime: string;
    endTime: string;
  }>({
    // 表格数据
    tableData: [],
    tableColumns: [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        align: 'center',
        width: 80,
      },
      {
        title: '名称',
        dataIndex: 'town',
        key: 'town',
        align: 'center',
        width: 120,
        customCell: (row, index, column) => {
          let isNoHzyh = row.town !== '汇总' ? true : false;
          let style = 'cursor:pointer;text-decoration: underline; color: blue;';
          let isNoZero = row[column.key] !== 0 ? true : false;
          return {
            style: `${isNoHzyh === true && isNoZero ? style : ''}`,
            class: 'cell-hover',
            innerHTML: `<span style=${style} >${row.town}</span>`,
            onClick: async () => {
              getDetailData(row);
            },
          };
        },
      },
        {
        title: '房屋总量',
        dataIndex: 'zcount',
        key: 'zcount',
        align: 'center',
        width: 140,
      },
      {
        title: '已核验房屋',
        dataIndex: 'zccount',
        key: 'zccount',
        align: 'center',
        width: 140,
      },
      {
        title: '核验进度',
        dataIndex: 'hy_pencent',
        key: 'hy_pencent',
        align: 'center',
        width: 140,
      },
      {
        title: '合格房屋',
        dataIndex: 'ssltdbfjsl',
        key: 'ssltdbfjsl',
        align: 'center',
        width: 140,
        customCell: (row, index, column) => {
          let isNoHzyh = row.town !== '汇总' ? true : false;
          let style = 'cursor:pointer;text-decoration: underline; color: blue;';
          let isNoZero = row[column.key] !== 0 ? true : false;
          return {
            style: `${isNoHzyh === true && isNoZero ? style : ''}`,
            class: 'cell-hover',
            onClick: async () => {
              getDetailData_1(row, index, column);
            },
          };
        },
      },
      {
        title: '当前合格率',
        dataIndex: 'dbl_pencent',
        key: 'dbl_pencent',
        align: 'center',
        width: 180,
      },
      {
        title: '发现不合格房屋',
        dataIndex: 'first_no_count',
        key: 'first_no_count',
        align: 'center',
        width: 180,
      },
      {
        title: '已整改',
        dataIndex: 'second_yes_count',
        key: 'second_yes_count',
        align: 'center',
        width: 150,
      },
      {
        title: '未整改',
        dataIndex: 'wwccount',
        key: 'wwccount',
        align: 'center',
        width: 180,
        customCell: (row, index, column) => {
          let isNoHzyh = row.town !== '汇总' ? true : false;
          let style = 'cursor:pointer;text-decoration: underline; color: blue;';
          let isNoZero = row[column.key] !== 0 ? true : false;
          return {
            style: `${isNoHzyh === true && isNoZero ? style : ''}`,
            class: 'cell-hover',
            onClick: async () => {
              getDetailData_2(row, index, column);
            },
          };
        },
      },
      {
        title: '整改率',
        dataIndex: 'zgl_pencent',
        key: 'zgl_pencent',
        align: 'center',
        width: 100,
      },
      {
        title: '当前不合格率',
        dataIndex: 'wdbl_percent',
        key: 'wdbl_percent',
        align: 'center',
        width: 180,
      },
      {
        title: '一层合格率',
        dataIndex: 'one_pencent',
        key: 'one_pencent',
        align: 'center',
        width: 150,
      },
      {
        title: '二层合格率',
        dataIndex: 'two_pencent',
        key: 'two_pencent',
        align: 'center',
        width: 150,
      },
      {
        title: '三层及以上合格率',
        dataIndex: 'three_pencent',
        key: 'three_pencent',
        align: 'center',
        width: 170,
      },
    ],
    id: null,
    loading: true,
    keyWorld: '',
    cityToken: '', // 判断是不是市区 110000 是北京市 展示搜索宽
    currentqx: '', // 当前行政区名称
    wscolsList: [{ wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }],
    endTime: '',
    startTime: '',
  });
  // 表格的 ref Dom名称
  let { tableData, loading } = toRefs(data);
  const getCode = async () => {
    if (startTime != null && startTime != '') {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      const sTime = moment(startTime).format('YYYY-MM-DD');
      const eTime = moment(endTime).format('YYYY-MM-DD');
      const start: any = dayjs(sTime);
      const end: any = dayjs(eTime);
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      startDate.value = start;
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      endDate.value = end;
    }

    checked.value = cked;
  };
  async function getData() {
    if (startDate.value == null) {
      let currentDate = moment().format('YYYY-MM-DD');
      const start: any = dayjs('2024-01-01');
      const end: any = dayjs(currentDate);
      startDate.value = start;
      endDate.value = end;
      getTime();
    }
    let params = {
      pageIndex: pageIndex.value,
      pageSize: pageSize.value,
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endtime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      cked: checked.value,
      roletype: role_type.value,
      xzqdm: xzqdm + '',
    };

    console.log('@市级参数', params);
    loading.value = true;
    let res: any = await HousetownStdList(params);
    console.log('@res--工作进入汇总表', res);

    if (res || res.items.length > 0) {
      loading.value = false;
      // console.log('data', data);
      // 算列和
      let bullding_count = total(res.items, 'zcount');
      let zccount = total(res.items, 'zccount');
      let ssltdbfjsl = total(res.items, 'ssltdbfjsl');
      let wwccount = total(res.items, 'wwccount');
      let index_count = res.items.length + 1;
      let dbl_pencent = '0%';
      if (ssltdbfjsl != 0) {
        dbl_pencent = ((ssltdbfjsl / zccount) * 100).toFixed(2) + '%';
      }
      let one = total(res.items, 'one');
      let one_ywccount = total(res.items, 'one_ywccount');
      let one_pencent = '0%';
      if (one_ywccount != 0) {
        one_pencent = ((one_ywccount / one) * 100).toFixed(2) + '%';
      }
      let two = total(res.items, 'two');
      let two_ywccount = total(res.items, 'two_ywccount');
      let two_pencent = '0%';
      if (two_ywccount != 0) {
        two_pencent = ((two_ywccount / two) * 100).toFixed(2) + '%';
      }
      let three = total(res.items, 'three');
      let three_ywccount = total(res.items, 'three_ywccount');
      let three_pencent = '0%';
      if (three_ywccount != 0) {
        three_pencent = ((three_ywccount / three) * 100).toFixed(2) + '%';
      }
      let wdbl_pencent = '0%';
      if (zccount != 0) {
        wdbl_pencent = ((wwccount / zccount) * 100).toFixed(2) + '%';
      }
      let first_no_count = total(res.items, 'first_no_count');
      let second_yes_count = total(res.items, 'second_yes_count');
      let zgl_pencent = '0%';
      if (first_no_count != 0) {
        zgl_pencent = ((second_yes_count / first_no_count) * 100).toFixed(2) + '%';
      }
      let yh_pencent = '0%';
      if (bullding_count != 0) {
        yh_pencent = ((zccount / bullding_count) * 100).toFixed(2) + '%';
      }
      let allObj = {
        town: '汇总',
        zcount: bullding_count,
        zccount: zccount,
        ssltdbfjsl: ssltdbfjsl,
        wwccount: wwccount,
        dbl_pencent: dbl_pencent,
        index: index_count,
        one_pencent: one_pencent,
        two_pencent: two_pencent,
        three_pencent: three_pencent,
        wdbl_percent: wdbl_pencent,
        first_no_count: first_no_count,
        second_yes_count: second_yes_count,
        zgl_pencent: zgl_pencent,
        hy_pencent: yh_pencent,
      };
      data.tableData = [...res.items, allObj];
      title.value = currentTitle + '';
    }
  }
  // 计算总数的方法
  function total(arr: any, item: any) {
    let total = arr.reduce((pre: any, cur: any) => {
      return parseInt(pre) + parseInt(cur[item]);
    }, 0);
    return total;
  }
  //下钻到乡镇
  const getDetailData = async (row: any) => {
    let params = {
      xzqdm: row.xzqdm,
      towndm: row.towndm,
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      currentTitle: '【' + row.xzq + '-' + row.town + '】双疏散通道统计情况',
      roletye: role_type.value,
    };
    store.setData(params); // 存入Pinia
    router.push({
      path: 'villagebaseHourse',
    });
  };
  const getDetailData_1 = async (row: any, isNoHzyh: boolean, isNoZero: boolean) => {
    router.push({
      path: '../targeted/hourseDetailLog',
      query: {
        xzq: row.xzq,
        xzqdm: row.xzqdm,
        towndm: row.towndm,
        town: row.town,
        floor: '1',
        currentTitle: row.xzq + '-' + row.town + '-' + '【双通道已达标】明细',
        startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
        roletype: role_type.value,
        nickname: nickname.value,
        txtKey: txtKeyWord.value,
        jsrysstd: '是',
      },
    });
  };
  //两层
  const getDetailData_2 = async (row: any) => {
    router.push({
      path: '../targeted/hourseDetailLog',
      query: {
        xzq: row.xzq,
        xzqdm: row.xzqdm,
        towndm: row.towndm,
        town: row.town,
        floor: '2',
        currentTitle: row.xzq + '-' + row.town + '-' + '【双通道未达标】明细',
        startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
        roletype: role_type.value,
        nickname: nickname.value,
        txtKey: txtKeyWord.value,
        jsrysstd: '否',
      },
    });
  };
  function getTime() {
    data.startTime = moment(startDate.value.$d).format('YYYY-MM-DD');
    data.endTime = moment(endDate.value.$d).format('YYYY-MM-DD');
    console.log('@查询参数 -- 开始时间', data.startTime);
    console.log('@查询参数 -- 结束时间', data.endTime);
  }
  function handleExport() {
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    downloadByUrl({
      url:
        uriBase +
        '/targeted/sysstdExportExcel?access_token=' +
        tk +
        '&cked=' +
        checked.value +
        '&xzqdm=' +
        xzqdm +
        '&roletype=' +
        role_type.value +
        '&startTime=' +
        startDate.value.format('YYYY-MM-DD') +
        '&endTime=' +
        endDate.value.format('YYYY-MM-DD'),
      target: '_blank',
    });
  }
  function searchBtn() {
    getTime();
    data.loading = true;
    if (
      (nickname.value != '' && nickname.value != null) ||
      (txtKeyWord.value != '' && txtKeyWord.value != null)
    ) {
      let title = '';
      if (
        nickname.value != '' &&
        nickname.value != null &&
        txtKeyWord.value != '' &&
        txtKeyWord.value != null
      ) {
        title = '【' + nickname.value + '-' + txtKeyWord.value + '】';
        let params = {
          startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
          endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
          nickname: nickname.value + '',
          txtKey: txtKeyWord.value,
          currentTitle: title,
        };
        router.push({
          path: '/utils/hcmxdetail',
          query: params,
        });
      } else if (nickname.value != '' && txtKeyWord.value == '') {
        title = '【' + nickname.value + '】核查情况';
        let params = {
          startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
          endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
          nickname: nickname.value + '',
          txtKey: txtKeyWord.value,
          currentTitle: title,
        };
        router.push({
          path: '/utils/hcmxdetail',
          query: params,
        });
      } else if (nickname.value == '' && txtKeyWord.value != '') {
        title = '【' + txtKeyWord.value + '】房屋情况';
        let params = {
          startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
          endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
          nickname: nickname.value + '',
          txtKey: txtKeyWord.value,
          currentTitle: title,
        };
        router.push({
          path: '/utils/hourse',
          query: params,
        });
      }
    } else {
      getData();
    }
  }
  function handleHourseExport() {
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    downloadByUrl({
      url: `${uriBase}/export/hourse/hourseExport?access_token=${tk}`,
      target: '_blank',
    });
  }
  function getUserInfo() {
    const userStore = useUserStore();
    userInfo.value = userStore?.getUserInfo;
  }
  const displayColumns = computed(() => {
    const { role } = userInfo.value;
    let arr: any[] = [];
    if (role === 'City') {
      // qx
      arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'czmc');
      return arr;
    } else if (role === 'Area') {
      // jz
      arr = data.tableColumns.filter((item) => item.key !== 'czmc' && item.key !== 'qxmc');
      return arr;
    } else if (role === 'Street') {
      // cun
      arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'qxmc');
      console.log('@Aarr', arr);
      return arr;
    } else {
      return data.tableColumns;
    }
  });
  const getTableHeight = () => {
    setTimeout(() => {
      detailTableHeight.value = window.innerHeight - 182;
      tableHeight.value = window.innerHeight - 292;
    });
  };
  const getBack = () => {
    router.go(-1);
  };
  onBeforeMount(() => {
    getUserInfo();
  });
  onMounted(() => {
    console.log('******基本信息统计初始化******');
    getCode();
    getData();
    getTableHeight();
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
  #map {
    height: calc(100vh - 140px);
  }

  .x-houseMng-search {
    z-index: 100;
    margin: 6px;
    position: absolute;
  }

  .root-house-mng-main {
    margin: 6px;
  }

  .x-village-tabs {
    //z-index: 100;
    //position: absolute;
    width: 60vw;
    margin-top: 6px;
    margin-left: 40px;
    //background-color: rgba(34, 34, 34, 0.6);
    :deep(.ant-form) {
      margin-top: 6px;
    }
  }
</style>

